package repeatword;

import java.io.*;

/*
 * Class for checking repeated words in a file.
 */

public class Word {
	
	BufferedWriter BW = null;
	FileInputStream FIS = null;
	FileWriter FW = null;
	char[] text; // text from Input.txt
	String[] words; // words from text
	char[] dels = {'\0', '\n', '	', ' ', ',', '.', '!', '-', '+', '=', ';', ':', '?', '&', '{', '}', '\\'};
	int t_length = 0;  // text length
	int w_length = 0 ; // word length
	
	public Word(String fName) throws IOException{	
		
		FIS = new FileInputStream(fName);		
		
	}

	/*
	 * Compare character, dels and if character is dels, then return true
	 */
	
	public boolean CompareCharDels(char ch){
		
		int Number_Dels = 17;
		
		for(int i = 0; i < Number_Dels; i++){
			if(ch == dels[i])
				return true;
		}
		return false;
	}

	/*
	 * Read a file and copy text
	 */
		 
	public void ReadFileCopy() throws IOException{
		
		text = new char[100];
		
		while(true){
			int Chara = FIS.read(); //read a file
			if(Chara < 0){
				break;
			}			
			text[t_length++] = (char)Chara; //change type int to char 	
		}		
	}
		
	/*
	 * Copy text to words
	 */
	
	public void CopyToWords(){
		
		int FirstOfWord = 0;
		int i ;
		words = new String[100];
		
		for(i=0; i<=t_length; i++)
		{			
			if(CompareCharDels(text[i])){
				words[w_length++] = String.copyValueOf(text,FirstOfWord,i-FirstOfWord);
				while(true){
					if(!CompareCharDels(text[i])||text[i]=='\0')
						break;
					else
						i++;					
				}
				FirstOfWord = i;
			}
		}		
		for(i=0; i<w_length; i++)
			System.out.println(i+" :"+words[i]);		
	}
	
	/*
	 * Compares and write repeated words to Output.txt
	 */
	
	public void Words() throws IOException{
		
		FW = new FileWriter("Output.txt");
		BW = new BufferedWriter(BW);
		int i;
		
		int lineCount = 1; //Count line number
		for(i=0; i<w_length-1; i++){
			
			if(words[i+1].equals("\r")){  
				lineCount++;				
				if(words[i].equals(words[i+2])){
					System.out.println("Repeated word on line "+lineCount+":"+words[i]+" "+words[i+2]);
					BW.write("Repeated word on line "+lineCount+":"+words[i]+" "+words[i+1]+" \r\n");
				}
				continue;
			}
			
			if(words[i].equals(words[i+1])){
				System.out.println("Repeated word on line "+lineCount+":"+words[i]+" "+words[i+1]);
				BW.write("Repeated word on line "+lineCount+":"+words[i]+" "+words[i+1]+" \r\n");
			}
		}
		
		BW.close();
		FIS.close();
	}


}

